class BluetoothLink {
    constructor() {

    }
    async linkDeviceByDeivceId(deviceId) {
        let res = await wx.createBLEConnection({deviceId})
        this.readyForReadOrWrite(deviceId)
        return res.errCode;
    }

    string2buffer(str) {
        let val = ""
        for (let i = 0; i < str.length; i++) {
            if (val === '') {
                val = str.charCodeAt(i).toString(16)
            } else {
                val += ',' + str.charCodeAt(i).toString(16)
            }
        }
        return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
            return parseInt(h, 16)
        })).buffer;
    }

    async readyForReadOrWrite(deviceId) {
        let connectDevice = await wx.getBLEDeviceServices({
            deviceId
        })
        let characteristics = await this.findWriteReadNotifyChannel(deviceId, connectDevice.services);
        console.log('findAll', characteristics);
        // connectDevice.services.map(async serviceItem => {
        //     let characteristicId = await wx.getBLEDeviceCharacteristics({
        //         deviceId,
        //         serviceId: serviceItem.uuid
        //     });
        //     console.log('characteristicData', characteristicId);
        // })
        // let characteristicId = await wx.getBLEDeviceCharacteristics({
        //   deviceId,
        //   serviceId: serviceId.uuid
        // })
        // console.log('characteristicData', characteristicId)

        // for (var i = 0; i < characteristicId.characteristics.length; i++) {
        //     if (characteristicId.characteristics[i].properties.notify) {
        //             notifyServicweId = serviceId.uuid;
        //             notifyCharacteristicsId = characteristicId.characteristics[i].uuid;
        //     }
        //     if (characteristicId.characteristics[i].properties.write) {
        //             writeServicweId = serviceId.uuid;
        //             writeCharacteristicsId = characteristicId.characteristics[i].uuid;
        //     } else if (characteristicId.characteristics[i].properties.read) {
        //             readServicweId = serviceId.uuid;
        //             readCharacteristicsId = characteristicId.characteristics[i].uuid;
        //     }
        // }
        // wx.writeBLECharacteristicValue({
        //     // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        //     deviceId: deviceId,
        //     // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        //     //serviceId: that.data.writeServicweId,
        //     serviceId: writeServicweId,
        //     // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
        //     //characteristicId: that.data.writeCharacteristicsId,
        //     characteristicId: writeCharacteristicsId,
        //     // 这里的value是ArrayBuffer类型
        //     value: this.string2buffer('A5'),
        //     success: function(res) {
        //         console.log('发送成功：' + JSON.stringify(res));
        //     },
        //     fail: function(res) {
        //         console.log("发送失败" + res.errMsg);
        //     },
        //     complete: function() {
        //         console.log("发送结束");
        //     }
        // });
        // 开启接受蓝牙广播
        await wx.notifyBLECharacteristicValueChange({
            state: true,
            deviceId,
            serviceId: characteristics.serviceId,
            characteristicId: characteristics.characteristicId
        })

        // 接受蓝牙广播回调
        wx.onBLECharacteristicValueChange(function(characteristic) {
            let hex = Array.prototype.map.call(new Uint8Array(characteristic.value), x => ('00' + x.toString(16)).slice(-2)).join('');
            console.log("接收到的十六进制数据：", hex);
        })

        // wx.readBLECharacteristicValue({
        //     // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
        //     deviceId: deviceId,
        //     // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        //     serviceId: readServicweId,
        //     // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
        //     characteristicId: readCharacteristicsId,
        //     success: function(res) {
        //       console.log('接收消息:', res);
        //     },
        //     fail: function(res) {
        //       console.log("接收消息错误:" + res.errMsg);
        //     },
        //     complete: function() {
        //       console.log("接收结束");
        //       wx.readBLECharacteristicValue({
        //         deviceId: deviceId,
        //         serviceId: readServicweId,
        //         characteristicId: readCharacteristicsId,
        //         success: function(res) {
        //           console.log('readBLECharacteristicValue', res)
        //         }
        //       });
        //     }
        //   })
    }

    // 返回可读可写可广播的信道
    findWriteReadNotifyChannel(deviceId, serviceList) {
        return new Promise((resolve, reject) => {
            let findChara = [];
            let serviceId = '';
            let characteristicId = '';
            serviceList.map(async serviceItem => {
                let characteristicId = await wx.getBLEDeviceCharacteristics({
                    deviceId,
                    serviceId: serviceItem.uuid
                });
                findChara = characteristicId.characteristics.filter(item => item.properties.read && item.properties.write && item.properties.notify);
                if(findChara.length > 0) {
                    console.log(111, findChara);
                    serviceId = serviceItem.uuid;
                    characteristicId = findChara[0].uuid;
                    resolve({
                        serviceId,
                        characteristicId
                    })
                }
            })
        });
    }

    // 把接收到的数据 拼成十六进制  每个包不超过 100毫秒
    splicingDataPackage() {
        
    }

    initScanBluetoothDevice() {
        return new Promise(async (resolve, reject) => {
            try {
                let openRes = await wx.openBluetoothAdapter();
                console.log(openRes);
                if(openRes.errMsg == 'openBluetoothAdapter:ok') {
                    resolve(openRes);
                }else{
                    reject(openRes);
                }
            }catch(e) {
                reject(e);
            }
        })
    }

    startScanDevice() {
        return new Promise(async (resolve, reject) => {
            let startRes = await wx.startBluetoothDevicesDiscovery({
                powerLevel: 'high'
            })
            if(startRes.errMsg == 'startBluetoothDevicesDiscovery:ok') {
                resolve(startRes);
            }else{
                reject(startRes);
            }
        })
    }

    checkBluetoothState() {
        return new Promise(async (resolve, reject) => {
            let openRes = await wx.getBluetoothAdapterState();
            console.log(openRes);
            resolve();
        })
    }

    getBlueDevice() {
        return new Promise((resolve, reject) => {
            wx.getBluetoothDevices({
                success: (res) => {
                    console.log('getBlueDevice', res);
                    resolve(res);
                },
                fail: (err) => {
                    console.log('getBlueDeviceErr', err);
                    resolve(err);
                }
            })
            
        })
    }

    listenOnDeviceFounded(callback) {
        wx.onBluetoothDeviceFound(res => {
            callback(res);
        });
    }

    stopBluetoothScan() {
        wx.stopBluetoothDevicesDiscovery();
        wx.offBluetoothDeviceFound();
        wx.offBluetoothAdapterStateChange();
        wx.closeBluetoothAdapter();
    }
}

module.exports = BluetoothLink;